var Mongoose = require('mongoose');

var userSequenceSchema = Mongoose.Schema({
    pageName: {
        type: String
    },
    timeSpent: {
        type: Number
    },
    user: {
        type: Mongoose.Schema.ObjectId,
        ref: 'User'
    }
}, {timestamps: true});

var userSequence = Mongoose.model('userSequence', userSequenceSchema);

userSequence.createSequence = function (newSequence, callback) {
    // userSequence.findOne({user: newSequence.user}, function (err, oldSequence) {
        // if (oldSequence) {
        //     oldSequence.sequence.push(newSequence.sequence[0]);
        //     oldSequence.totalTime += newSequence.sequence[0].timeSpent;
        //     oldSequence.save(callback);
        // } else {
            newSequence.save(callback);
        // }
    // });
};

userSequence.getUserSequence = function (params, callback) {
    var searchMatch = {user: Mongoose.Types.ObjectId(params.userId)};
    userSequence.aggregate([
        {$match: searchMatch},
        {
            $group: {
                _id: "$user",
                items: {
                    $push: {
                        "_id": "$_id",
                        "updatedAt": "$updatedAt",
                        "createdAt": "$createdAt",
                        "pageName": "$pageName",
                        "timeSpent": "$timeSpent",
                        "user": "$user"
                    }
                }
            }
        }
    ], callback);
};

userSequence.getUserSequenceCSV = function (params, callback) {
    var searchMatch = {user: Mongoose.Types.ObjectId(params.userId)};
    userSequence.aggregate([
        {$match: searchMatch},
        {
            $lookup: {
                "from": "users",
                "localField": "user",
                "foreignField": "_id",
                "as": "users"
            }
        },
        {
            $unwind: "$users"
        },
        {
            $project:
            {
                "name": {$concat: ["$users.firstName", " ", {$ifNull: ["$users.lastName", " "]}]},
                "_id": "$_id",
                "updatedAt": "$updatedAt",
                "createdAt": "$createdAt",
                "pageName": "$pageName",
                "timeSpent": "$timeSpent",
                "user": "$user"
            }
        }
    ], callback);
};

userSequence.getAllUsersSequence = function (callback) {
    userSequence.find({}, callback);
};

module.exports = userSequence;